package com.chanyachting.emall.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;

import com.chanyachting.emall.dao.NewsactivityDAO;
import com.chanyachting.emall.dao.PeriodicalDAO;
import com.chanyachting.emall.domain.Newsactivity;
import com.chanyachting.emall.domain.Periodical;
import com.chanyachting.emall.service.NewsActivityService;
import com.chanyachting.emall.util.DateUtil;

public class NewsActivityServiceImpl implements NewsActivityService {
	
	
	private NewsactivityDAO nadao;
	
	
	public NewsActivityServiceImpl(){
		
		
		this.nadao=new NewsactivityDAO();
		
	}
	
	public boolean createNewsActivity(Newsactivity na) {
		// TODO Auto-generated method stub
		this.nadao.save(na);
		
		return true;
	}

	public boolean deleteNewsActivity(Newsactivity na) {
		// TODO Auto-generated method stub
		this.nadao.delete(na);
		
		return true;
	}

	public List<Newsactivity> getAllNewsActivity() {
		// TODO Auto-generated method stub
		return this.nadao.queryAllNewsActivity();
	}

	public List<Newsactivity> getMemberNewsActivity(Integer memberId) {
		// TODO Auto-generated method stub
		return this.nadao.queryNewsActivityByMemberId(memberId);
	}

	public Newsactivity getOneNewsActivity(Integer id) {
		// TODO Auto-generated method stub
		Newsactivity na= (Newsactivity) this.nadao.load(Newsactivity.class, id);
		
		return na;
	}

	public boolean updateNewsActivity(Newsactivity na) {
		// TODO Auto-generated method stub
		this.nadao.update(na);
		
		return true;
	}



	public void refresh(Newsactivity na) {
		// TODO Auto-generated method stub
		
		this.nadao.refresh(na);
	}



	public List<Newsactivity> getMemberNotReleasedNewsActivity(Integer memberId) {
		// TODO Auto-generated method stub
		return this.nadao.queryNotReleasedNewsActivityByMemberId(memberId);
	}



	public List<Newsactivity> getMemberReleasedNewsActivity(Integer memberId) {
		// TODO Auto-generated method stub
		return this.nadao.queryReleasedNewsActivityByMemberId(memberId);
	}



	public void delrelease(Newsactivity na) {
		// TODO Auto-generated method stub
		
		this.nadao.updateStatus(na.getId(), "00");
		
	}


	/**
	 * 发布新闻活动
	 */
	public void release(Newsactivity na) {
		
		na=this.getOneNewsActivity(na.getId());
		
		na.setStatus("01");   //修改状态为提交审核
		
		na.setReleaseDate(DateUtil.getDate());
		
		this.updateNewsActivity(na);
		
//		//检查会员是否购买对应功能服务
//		List<Memberorderservices> list=new Memberorderservices().listByOptionTypeAndActivityAndMemberId(na.getMemberId(), "02");
//		
//		//如果会员有对应类型的功能服务 
//		if(list!=null && list.size()>0){
//			
//			Memberorderservices mos=null;
//			
//			MemberorderservicesBO mosbo=null;
//			
//			//获取第一个有效的功能服务
//			for(int i=0;i<list.size();i++){
//				
//				mos=(Memberorderservices)list.get(i);  
//				
//				mosbo=new MemberorderservicesBO(mos);
//				
//				if(mosbo.checkMemberService()){
//					
//					break;
//					
//				}else{
//					
//					mos=null;
//				}
//			}
//			
//			//如果功能服务有效
//			if(mos!=null){
//				
//				na=this.getOneNewsActivity(na.getId());
//				
//				na.setStatus("01");   //修改状态为提交审核
//				
//				na.setReleaseDate(DateUtil.getDate());
//				
//				this.updateNewsActivity(na);
//				
//				//功能服务后续处理
//				mosbo.executeMemberServicd();
//			}
//		}
		
		//this.nadao.updateStatus(na.getId(), "01");
	}



	public List<Newsactivity> getNewsActivityByChannelId(Integer channelId,int pageNo,int pageSize) {
		// TODO Auto-generated method stub
		return this.nadao.queryNewsActivityByChannelId(channelId,pageNo,pageSize);
	}



	public List<Newsactivity> getNewsActivityBySubChannelId(Integer subChannelId,int pageNo,int pageSize) {
		// TODO Auto-generated method stub
		return this.nadao.queryNewsActivityBySubChannelId(subChannelId,pageNo,pageSize);
	}



	public List<Newsactivity> getNewsActivityByNewsid(Integer newsId) {
		// TODO Auto-generated method stub
		return this.nadao.queryNewsActivityDetailsById(newsId);
	}

	public int getAllNewsactivityById(String type, String id) {
		return this.nadao.getAllNewsactivityById(type, id);
	}
	
	@SuppressWarnings("unchecked")
	public Newsactivity getOneNewsactivityById(String memberId,String id) {
		String strSql = "from Newsactivity where id = ? and memberId = ?";
		
		List<Newsactivity> newsList = this.nadao.find(strSql, new String[]{id,memberId});
		
		if (newsList == null || newsList.size() == 0) {
			return null;
		}
		
		return newsList.get(0);
	}

	@SuppressWarnings("unchecked")
	public List<Newsactivity> getNewsBySubChannalId(String subChannalId,int currentPage,int pageSize,boolean isRecommend) {
		String sql = "from Newsactivity where subChannelId = ?";
		if (isRecommend) {
			sql = sql + " and recommend='1'";
		} else {
			sql = sql + " and status='01'";
		}
		sql = sql + " order by releaseDate desc";
		Query q = this.nadao.createQuery(sql);
		
		q.setMaxResults(pageSize);
		q.setFirstResult((currentPage-1) * pageSize);
		q.setString(0, subChannalId);
		
		List<Newsactivity> newsList = q.list();
		if (newsList != null && newsList.size() != 0) {
			newsList = editPeriodical(newsList);
		}
		return newsList;
	}
	
	public int getNewsCountBySubChannalId(String subChannalId,boolean isRecommend) {
		String sql = "select count(*) from Newsactivity where subChannelId = ?";
		if (isRecommend) {
			sql = sql + " and recommend='1'";
		} else {
			sql = sql + " and status='01'";
		}
		
		return (Integer)this.nadao.find(sql, new String[]{subChannalId}).get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<Newsactivity> getNewsByChannalId(String channalId,int currentPage,int pageSize,boolean isRecommend) {
		
		String sql = "from Newsactivity where channelId = ?";
		if (isRecommend) {
			sql = sql + " and recommend='1'";
		} else {
			sql = sql + " and status='01'";
		}
		sql = sql + " order by releaseDate desc";
		Query q = this.nadao.createQuery(sql);
		q.setString(0, channalId);
		q.setMaxResults(pageSize);
		q.setFirstResult((currentPage-1) * pageSize);
		List<Newsactivity> newsList = q.list();
		if (newsList != null && newsList.size() != 0) {
			newsList = editPeriodical(newsList);
		}
		
		return newsList;
	}
	
	public int getNewsCountByChannalId(String channalId,boolean isRecommend) {
		String sql = "select count(*) from Newsactivity where channelId = ?";
		if (isRecommend) {
			sql = sql + " and recommend='1'";
		} else {
			sql = sql + " and status='01'";
		}
		return (Integer)this.nadao.find(sql, new String[]{channalId}).get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<Newsactivity> getNewsByKeywords1(Newsactivity news,int currentPage,int pageSize,Periodical pd,boolean isRecommend) {
		
		Query q = this.getQueryListByChannelId(news,currentPage,pageSize,pd,isRecommend);
		
		List<Newsactivity> newsList = q.list();
		if (newsList != null && newsList.size() != 0) {
			newsList = editPeriodical(newsList);
		}
		
		return newsList;
	}
	
	@SuppressWarnings("unchecked")
	public List<Newsactivity> getNewsByKeywords2(Newsactivity news,int currentPage,int pageSize,Periodical pd,boolean isRecommend) {
		
		Query q = this.getQueryListBySubChannelId(news,currentPage,pageSize,pd,isRecommend);
		
		List<Newsactivity> newsList = q.list();
		if (newsList != null && newsList.size() != 0) {
			newsList = editPeriodical(newsList);
		}
		
		return newsList;
	}
	
	public int getNewsCountByKeywords1(Newsactivity news,Periodical pd,boolean isRecommend) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(n) from Newsactivity n,Periodical p where n.title like ? and n.channelId=?");
		if (isRecommend) {
			sql.append(" and n.recommend='1'");
		} else {
			sql.append(" and n.status='01'");
		}
		if (pd != null) {
			sql.append(" and n.periodical = p.magazineId and p.status ='01'");
			if (null != pd.getYear() && !"".equals(pd.getYear())) {
				sql.append(" and p.year = ?");
			}
			if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				sql.append(" and p.startMonth = ?");
			}
		}
		Query q = this.nadao.createQuery(sql.toString());
		q.setString(0, "%" + news.getTitle() + "%");
		q.setInteger(1, news.getChannelId());
		if (pd != null) {
			if (null != pd.getYear() && !"".equals(pd.getYear()) && null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getYear());
				q.setString(3,pd.getStartMonth());
			} else if (null != pd.getYear() && !"".equals(pd.getYear())) {
				q.setString(2, pd.getYear());
			} else if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getStartMonth());
			}
		}
		
		return (Integer)q.list().get(0);
	}
	
	/*
	 * 1.新闻对象
	 * 2.期刊对象
	 * 3.true:列出审核通过的新闻      false：列出上架状态的新闻
	 */
	public int getNewsCountByKeywords2(Newsactivity news,Periodical pd,boolean isRecommend) {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(n) from Newsactivity n,Periodical p where n.title like ? and n.subChannelId=?");
		if (isRecommend) {
			sql.append(" and n.recommend='1'");
		} else {
			sql.append(" and n.status='01'");
		}
		if (pd != null) {
			sql.append(" and n.periodical = p.magazineId and p.status ='01'");
			if (null != pd.getYear() && !"".equals(pd.getYear())) {
				sql.append(" and p.year = ?");
			}
			if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				sql.append(" and p.startMonth = ?");
			}
		}
		Query q = this.nadao.createQuery(sql.toString());
		q.setString(0, "%" + news.getTitle() + "%");
		q.setInteger(1, news.getChannelId());
		if (pd != null) {
			if (null != pd.getYear() && !"".equals(pd.getYear()) && null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getYear());
				q.setString(3,pd.getStartMonth());
			} else if (null != pd.getYear() && !"".equals(pd.getYear())) {
				q.setString(2, pd.getYear());
			} else if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getStartMonth());
			}
		}
		
		return (Integer)q.list().get(0);
	}
	
	@SuppressWarnings("unchecked")
	public Newsactivity getOneNewsById(String id) {
		String sql = "from Newsactivity where id = ?";
		List<Newsactivity> newsList = this.nadao.find(sql,new String[]{id});
		
		if (newsList == null || newsList.size() != 1) {
			return null;
		}
		Newsactivity tmpNews = new Newsactivity();
		tmpNews = newsList.get(0);
		int readNums = tmpNews.getReadNums() == null?0:tmpNews.getReadNums();
		readNums ++;
		tmpNews.setReadNums(readNums);
		this.nadao.update(tmpNews);
		this.nadao.refresh(tmpNews);
		
		Integer periodical = newsList.get(0).getPeriodical();
		Integer tmpZero = 0;
		if (periodical != null && !"".equals(periodical) && !tmpZero.equals(periodical)) {
			PeriodicalDAO pDao = new PeriodicalDAO();
			String sql2 = "from Periodical where magazineId = ? and status = '01'";
			List<Periodical> pList = pDao.find(sql2,new String[]{periodical.toString()});
			Periodical p = null;
			if (pList != null && pList.size() == 1) {
				p = pList.get(0);
			}
			String qikanhao = p.getYear() + " ";
			if (p.getStartMonth() != null && p.getStartMonth().equals(p.getEndMonth())) {
				qikanhao = p.getStartMonth() + "月刊" + "（总第" + p.getSerialNumber() + "期）";
			} else {
				qikanhao = p.getStartMonth() + "/" + p.getEndMonth() + "月刊" + "（总第" + p.getSerialNumber() + "期）";
			}
			newsList.get(0).setReleaseDate(qikanhao);
		}
		
		return newsList.get(0);
		
	}
	
	private Query getQueryListByChannelId(Newsactivity news,int currentPage,int pageSize,Periodical pd,boolean isRecommend) {
		StringBuffer sql = new StringBuffer();
		sql.append("select n from Newsactivity n,Periodical p where n.title like ? and n.channelId=?");
		if (isRecommend) {
			sql.append(" and n.recommend='1'");
		} else {
			sql.append(" and n.status='01'");
		}
		if (pd != null) {
			sql.append(" and n.periodical = p.magazineId and p.status ='01'");
			if (null != pd.getYear() && !"".equals(pd.getYear())) {
				sql.append(" and p.year = ?");
			}
			if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				sql.append(" and p.startMonth = ?");
			}
		}
		sql.append("  order by releaseDate desc");
		Query q = this.nadao.createQuery(sql.toString());
		q.setString(0, "%" + news.getTitle() + "%");
		q.setInteger(1, news.getChannelId());
		if (pd != null) {
			if (null != pd.getYear() && !"".equals(pd.getYear()) && null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getYear());
				q.setString(3,pd.getStartMonth());
			} else if (null != pd.getYear() && !"".equals(pd.getYear())) {
				q.setString(2, pd.getYear());
			} else if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
					q.setString(2, pd.getStartMonth());
			}
		}
		q.setMaxResults(pageSize);
		q.setFirstResult((currentPage-1) * pageSize);
		return q;
	}
	
	private Query getQueryListBySubChannelId(Newsactivity news,int currentPage,int pageSize,Periodical pd,boolean isRecommend) {
		StringBuffer sql = new StringBuffer();
		sql.append("select n from Newsactivity n,Periodical p where n.title like ? and n.subChannelId=?");
		if (isRecommend) {
			sql.append(" and n.recommend='1'");
		} else {
			sql.append(" and n.status='01'");
		}
		if (pd != null) {
			sql.append(" and n.periodical = p.magazineId and p.status ='01'");
			if (null != pd.getYear() && !"".equals(pd.getYear())) {
				sql.append(" and p.year = ?");
			}
			if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				sql.append(" and p.startMonth = ?");
			}
		}
		sql.append("  order by releaseDate desc");
		Query q = this.nadao.createQuery(sql.toString());
		q.setString(0, "%" + news.getTitle() + "%");
		q.setInteger(1, news.getSubChannelId());
		if (pd != null) {
			if (null != pd.getYear() && !"".equals(pd.getYear()) && null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
				q.setString(2, pd.getYear());
				q.setString(3,pd.getStartMonth());
			} else if (null != pd.getYear() && !"".equals(pd.getYear())) {
				q.setString(2, pd.getYear());
			} else if (null != pd.getStartMonth() && !"".equals(pd.getStartMonth())) {
					q.setString(2, pd.getStartMonth());
			}
		}
		q.setMaxResults(pageSize);
		q.setFirstResult((currentPage-1) * pageSize);
		return q;
	}
	
	@SuppressWarnings("unchecked")
	private List<Newsactivity> editPeriodical(List<Newsactivity> newsList) {
		
		List<Newsactivity> tmpList = new ArrayList<Newsactivity>();
		for (int i=0;i<newsList.size();i++) {
			Integer periodical = newsList.get(i).getPeriodical();
			Integer intZero = 0;
			if (periodical != null && !"".equals(periodical) && !intZero.equals(periodical)) {
				PeriodicalDAO pDao = new PeriodicalDAO();
				String sql2 = "from Periodical where magazineId = ? and status = '01'";
				List<Periodical> pList = pDao.find(sql2,new String[]{periodical.toString()});
				Periodical p = null;
				if (pList != null && pList.size() == 1) {
					p = pList.get(0);
				}
				String qikanhao = p.getYear() + " ";
				if (p.getStartMonth() != null && p.getStartMonth().equals(p.getEndMonth())) {
					qikanhao = p.getStartMonth() + "月刊" + "（总第" + p.getSerialNumber() + "期）";
				} else {
					qikanhao = p.getStartMonth() + "/" + p.getEndMonth() + "月刊" + "（总第" + p.getSerialNumber() + "期）";
				}
				newsList.get(i).setReleaseDate(qikanhao);
			}
			tmpList.add(newsList.get(i));
		}
		return tmpList;
	}
}
